package jee.boot.common.service;

import jee.boot.common.basic.CrudService;
import jee.boot.common.dao.SystemConfigDao;
import jee.boot.entity.system.Filter;
import jee.boot.entity.system.SystemConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 账户配置信息
 */
@Service
public class SystemConfigService extends CrudService<SystemConfigDao, SystemConfig> {
    @Cacheable(value = "sysConfig", key = "#entity.entityKey")
    public SystemConfig getByCode(SystemConfig entity) {
        entity.addFilter(new Filter("code", "=", entity.getCode()));
        List<SystemConfig> list = findList(entity);
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Caching(evict = {
            @CacheEvict(value = "sysConfig", key = "#entity.entityKey"),
    })
    @Override
    public void update(SystemConfig entity) {
        super.update(entity);
    }

    @Caching(evict = {
            @CacheEvict(value = "sysConfig", key = "#entity.entityKey"),
    })
    @Override
    public void delete(SystemConfig entity) {
        super.delete(entity);
    }

    /**
     * 按code将配置属性转换为map
     *
     * @param entity
     * @return
     */
    public Map<String, SystemConfig> findAsMap(SystemConfig entity) {
        Map<String, SystemConfig> map = new HashMap<>();
        List<SystemConfig> list = super.findList(entity);
        if (list != null && !list.isEmpty()) {
            list.forEach(accountConfig -> {
                map.put(accountConfig.getCode(), accountConfig);
            });
        }
        return map;
    }

    /**
     * 根据code获取对应的配置的值
     *
     * @param code
     * @param defaultValue
     * @return
     */
    public String getValueByCode(String code, Object defaultValue) {
        Map<String, SystemConfig> map = findAsMap(new SystemConfig());
        return getValueByCode(map, code, defaultValue);
    }

    /**
     * 根据code获取对应的配置的值
     *
     * @param code
     * @param defaultValue
     * @return
     */
    public String getValueByCode(Map<String, SystemConfig> map, String code, Object defaultValue) {
        SystemConfig config = map.get(code);
        if (config == null) {
            logger.warn("在SystemConfig中没有设置'" + code + "',使用默认值" + defaultValue);
            return String.valueOf(defaultValue);
        } else {
            return config.getValue();
        }
    }
}
